package com.scnu.edu.controller;

import com.scnu.edu.dto.MovieDTO;
import com.scnu.edu.entity.*;
import com.scnu.edu.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import jakarta.servlet.http.HttpSession;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/movie")
public class MovieController {
    @Autowired
    private MovieService movieService;
    
    @Autowired
    private ActorService actorService;
    
    @Autowired
    private DirectorService directorService;

    @Autowired
    private RatingService ratingService;

    @Autowired
    private UserService userService;

    @RequestMapping("/detail")
    public String detail(Integer id, Model model, HttpSession session) {
        Movie movie = movieService.getById(id);
        User user = (User) session.getAttribute("user");
        boolean canPlay = !movie.getIsVip() || (user != null && user.getIsVip());
        
        MovieDTO movieDTO = new MovieDTO(movie);
        
        // 获取导演和主演信息
        List<Director> directors = directorService.findDirectorsByMovieId(id.longValue());
        List<Actor> actors = actorService.findActorsByMovieId(id.longValue());
        
        // 获取导演和主演的其他作品
        List<Movie> directorMovies = directors.isEmpty() ? new ArrayList<>() :
            movieService.findMoviesByDirectorId(directors.get(0).getId());
        List<Movie> actorMovies = actors.isEmpty() ? new ArrayList<>() :
            movieService.findMoviesByActorId(actors.get(0).getId());

        // 获取评论列表
        List<Rating> ratings = ratingService.getRatingsByMovieId(id.longValue());
        // 为每个评论添加用户信息
        for (Rating rating : ratings) {
            rating.setUser(userService.getById(rating.getUserId()));
        }
        
        // 获取排行榜数据
        List<MovieDTO> weeklyRanking = movieService.getWeeklyRanking();
        List<MovieDTO> monthlyRanking = movieService.getMonthlyRanking();
        List<MovieDTO> ratingRanking = movieService.getRatingRanking();
        
        model.addAttribute("movie", movieDTO);
        model.addAttribute("canPlay", canPlay);
        model.addAttribute("directors", directors);
        model.addAttribute("actors", actors);
        model.addAttribute("directorMovies", directorMovies);
        model.addAttribute("actorMovies", actorMovies);
        model.addAttribute("ratings", ratings);
        model.addAttribute("canPlay", canPlay);
        model.addAttribute("weeklyRanking", weeklyRanking);
        model.addAttribute("monthlyRanking", monthlyRanking);
        model.addAttribute("ratingRanking", ratingRanking);
        
        return "movie/detail";
    }

    @RequestMapping("/ranking")
    public String ranking(@RequestParam(defaultValue = "week") String type, Model model) {
        List<MovieDTO> movies;
        switch (type) {
            case "week":
                movies = movieService.getWeeklyRanking();
                break;
            case "month":
                movies = movieService.getMonthlyRanking();
                break;
            case "all":
                movies = movieService.getAllTimeRanking();
                break;
            case "rating":
                movies = movieService.getRatingRanking();
                break;
            default:
                movies = movieService.getWeeklyRanking();
        }
        
        model.addAttribute("movies", movies);
        model.addAttribute("type", type);
        return "movie/ranking";
    }

    @RequestMapping("/actor/{id}")
    public String actorMovies(@PathVariable Long id, @RequestParam(defaultValue = "1") Integer pageNo, Model model) {
        Actor actor = actorService.getById(id);
        List<Movie> movies = movieService.findMoviesByActorId(id);
        List<Movie> recommendations = movieService.getRecommendationsByActor(id);
        
        List<MovieDTO> movieDTOs = movies.stream()
            .map(MovieDTO::new)
            .collect(Collectors.toList());
            
        List<MovieDTO> recommendationDTOs = recommendations.stream()
            .map(MovieDTO::new)
            .collect(Collectors.toList());
        
        model.addAttribute("creator", actor);
        model.addAttribute("type", "actor");
        model.addAttribute("movies", movieDTOs);
        model.addAttribute("recommendations", recommendationDTOs);
        model.addAttribute("currentPage", pageNo);
        model.addAttribute("pageCount", (movies.size() + 11) / 12);
        return "movie/creator";
    }

    @RequestMapping("/director/{id}")
    public String directorMovies(@PathVariable Long id, @RequestParam(defaultValue = "1") Integer pageNo, Model model) {
        Director director = directorService.getById(id);
        List<Movie> movies = movieService.findMoviesByDirectorId(id);
        List<Movie> recommendations = movieService.getRecommendationsByDirector(id);
        
        List<MovieDTO> movieDTOs = movies.stream()
            .map(MovieDTO::new)
            .collect(Collectors.toList());
            
        List<MovieDTO> recommendationDTOs = recommendations.stream()
            .map(MovieDTO::new)
            .collect(Collectors.toList());
        
        model.addAttribute("creator", director);
        model.addAttribute("type", "director");
        model.addAttribute("movies", movieDTOs);
        model.addAttribute("recommendations", recommendationDTOs);
        model.addAttribute("currentPage", pageNo);
        model.addAttribute("pageCount", (movies.size() + 11) / 12);
        return "movie/creator";
    }

    @GetMapping("/{id}")
    public String getMovieById(@PathVariable Long id) {
        return "redirect:/movie/detail?id=" + id;
    }

    @RequestMapping("/search")
    public String search(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                        @RequestParam(name = "keyword", defaultValue = "") String keyword,
                        @RequestParam(name = "category", required = false) Long categoryId,
                        @RequestParam(name = "region", required = false) Long regionId,
                        @RequestParam(name = "creator", required = false) String creator,
                        @RequestParam(name = "sort", defaultValue = "release_date") String sort,
                        Model model) {
        Integer pageSize = 12;
        Map<String, Object> map = movieService.advancedSearch(keyword, categoryId, regionId, creator, sort, pageNo, pageSize);
        model.addAttribute("movies", map.get("records"));
        model.addAttribute("currentPage", pageNo);
        model.addAttribute("pageCount", map.get("pageCount"));
        model.addAttribute("keyword", keyword);
        model.addAttribute("selectedCategory", categoryId);
        model.addAttribute("selectedRegion", regionId);
        model.addAttribute("sort", sort);
        
        // 确保分页参数传递到视图
        model.addAttribute("pageNo", pageNo);
        
        // 获取分类和地区列表
        model.addAttribute("categories", movieService.getAllCategories());
        model.addAttribute("regions", movieService.getAllRegions());
        
        return "movie/search";
    }

    @GetMapping("/play/{id}")
    public ResponseEntity<Resource> playMovie(@PathVariable Long id, HttpSession session) throws IOException {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "请先登录");
        }

        Movie movie = movieService.getById(id);
        if (movie.getIsVip() && !user.getIsVip()) {
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "该视频为VIP专享，请开通VIP");
        }

        // 构造完整的资源路径
        String moviePath = "static/" + movie.getPlayUrl();

        // 使用ClassPathResource加载资源
        Resource resource = new ClassPathResource(moviePath);

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("video/mp4"))
                .body(resource);
    }

}